package org.example.rabbitmq.workWithFairDispatch;


import com.rabbitmq.client.*;

import java.util.concurrent.TimeUnit;

public class Work2 {
    public static void main(String[] args) throws Exception {
        // 1: 创建连接工厂，设置连接属性
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("127.0.0.1");
        connectionFactory.setPort(5672);
        connectionFactory.setVirtualHost("/");
        connectionFactory.setUsername("guest");
        connectionFactory.setPassword("guest");

        // 2: 创建连接，获取通道
        Connection connection = connectionFactory.newConnection("消费者2");
        Channel channel = connection.createChannel();

        // 同一时刻服务器只会发送一条消息给消费者
        channel.basicQos(1);

        DeliverCallback deliverCallback = (consumerTag, delivery) -> {
            try {
                // 加一个睡眠，模拟消费者1消费慢
                TimeUnit.MILLISECONDS.sleep(100);
                System.out.println("Work2-收到消息是" + new String(delivery.getBody(), "UTF-8"));
                // 确认消息消费，参数1：确认队列中哪个具体消息，参数2：是否开启多个消息同时确认
                channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        };

        // 接收消息，开启确认机制，设置autoAck为false
        channel.basicConsume("work-queue2", false, deliverCallback, consumerTag -> {
        });

    }
}
